from sqlalchemy.orm import Session
from fastapi import HTTPException, status
from typing import List

from ..models.tag import Tag
from ..schemas.tag import TagCreate, TagUpdate


class TagService:
    """标签服务"""
    
    @staticmethod
    def get_tags(user_id: int, db: Session) -> List[Tag]:
        """获取所有标签"""
        tags = db.query(Tag).filter(Tag.user_id == user_id).all()
        return tags
    
    @staticmethod
    def get_tag(tag_id: int, user_id: int, db: Session) -> Tag:
        """获取单个标签"""
        tag = db.query(Tag).filter(
            Tag.id == tag_id,
            Tag.user_id == user_id
        ).first()
        
        if not tag:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="标签不存在"
            )
        
        return tag
    
    @staticmethod
    def create_tag(tag_data: TagCreate, user_id: int, db: Session) -> Tag:
        """创建标签"""
        # 检查标签名是否已存在
        existing_tag = db.query(Tag).filter(
            Tag.user_id == user_id,
            Tag.name == tag_data.name
        ).first()
        
        if existing_tag:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="标签名已存在"
            )
        
        tag = Tag(
            user_id=user_id,
            name=tag_data.name,
            color=tag_data.color
        )
        
        db.add(tag)
        db.commit()
        db.refresh(tag)
        return tag
    
    @staticmethod
    def update_tag(tag_id: int, tag_data: TagUpdate, user_id: int, db: Session) -> Tag:
        """更新标签"""
        tag = TagService.get_tag(tag_id, user_id, db)
        
        update_data = tag_data.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(tag, field, value)
        
        db.commit()
        db.refresh(tag)
        return tag
    
    @staticmethod
    def delete_tag(tag_id: int, user_id: int, db: Session) -> None:
        """删除标签"""
        tag = TagService.get_tag(tag_id, user_id, db)
        db.delete(tag)
        db.commit()

